import URL from 'url';
import fs from 'fs';
import { login, getOssSts2, upload } from './../apis/makaApi';
import { md5, hmac } from '../utils/encryption';
import { each, randomStr } from '../utils';

const canonicalizedHeaders = (headers) => {
  const arr: string[] = [];
  each(headers, name => {
      if (name.match(/^x-oss-/)){
          arr.push(name);
      }
  });
  arr.sort(function(a, b) {
      return a.toLowerCase() < b.toLowerCase() ? -1 : 1;
  });

  const parts: string[] = [];
  arr.forEach(function(name) {
      parts.push(name.toLowerCase() + ':' + headers[name]);
  });
  return parts.join('\n');
}

const stringToSign = (headers, resource) => {
	const parts: string[] = [];
	parts.push(headers.method);
	parts.push(headers['Content-MD5'] || '');
	parts.push(headers['Content-Type'] || '');
	parts.push(headers['presigned-expires'] || headers['x-oss-date'] || headers['Date'] || '');
	parts.push(canonicalizedHeaders(headers));
    parts.push(resource);
	return parts.join('\n');
}

const sign = (token, headers, resource) => {
  var string = stringToSign(headers, resource);
  var signature = hmac(token.AccessKeySecret, string, 'base64', 'sha1');
	return signature;
};

const getOssHeader = (token, data, resource, contentType) => {
	var credentials = token.token.Credentials;
	var ContentMD5 = md5(data, 'base64');
	var header = {
		'method': 'PUT',
		'Content-MD5': ContentMD5,
		'Content-Type': contentType,
		'x-oss-date': (new Date()).toUTCString(),
		'x-oss-security-token': credentials.SecurityToken,
		'x-sdk-client': '',
    Authorization: ''
	};
	var signature = sign(credentials, header, resource);
	var auth = 'OSS ' + credentials.AccessKeyId + ':' + signature;
	header.Authorization = auth;
	return header;
}

class MakaOss {
  userName= '1248198090@qq.com';
  userPwd= 'makazcj';
  ossSts2;

  constructor() {
    this.init();
  }

  async init() {
    await this.getOssToken();
  }

  async getOssToken() {
    try {
      const res = await login(this.userName, this.userPwd);
      if (res.data.code === 200) {
        const token = res.data.data.token;
        const cookies = res.headers['set-cookie'] as string[];
        const tokenRes = await getOssSts2(token, cookies);
        if (tokenRes.data.code === 200) {
          this.ossSts2 = tokenRes.data.data;
        }
      }
    } catch (error) {
      
    }
  }

  uploadFile(filePath) {
    try {
      const binary = fs.readFileSync(filePath);
      const suffixName = /\.[^\.]+$/.exec(filePath); 
      const path = '/' + this.ossSts2.uploadPath +'audio/' + randomStr() + suffixName;
      const resource = '/' + this.ossSts2.bucket + path;
      const header = getOssHeader(this.ossSts2, binary, resource, 'audio/mp3');
      const param = URL.parse(this.ossSts2.hostId);
      var url = param.protocol + '//' + this.ossSts2.bucket + '.' + param.host + path;
      console.log('url', url)
      return upload(url, binary, header).then((res)=> {
        console.log(url);
        console.log(res);
      });
    } catch (e) {
      console.log('error', e);
    }
  }
};

export default MakaOss;